//index.js
//获取应用实例
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    userData: {
      'encryptedData': '',
      'iv': '',
      'signature': '',
      'rawData': '',
      'code':''
    },
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

onShow:function(){
  let userInfo = wx.getStorageSync('userinfo');
  this.setData({
    userInfo: userInfo,
  });
},

  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  call:function(){
    wx.makePhoneCall({
      phoneNumber: '12345678900', //此号码并非真实电话号码，仅用于测试
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })
  },
  getUserInfo: function (e) {
   

    console.log(e);
    app.globalData.userInfo = e.detail.userInfo

    let user = this.data.userData;
    user.encryptedData = e.detail.encryptedData;
    user.iv = e.detail.iv;
    user.signature = e.detail.signature;
    user.rawData = e.detail.rawData;
    let that = this;
    wx.getStorage({
      key: 'code',
      success: function (res) {
        console.log(res.data);
        user.code = res.data;
        that.setData({
          userInfo: e.detail.userInfo,
          userData: user,
          hasUserInfo: true
        });



        util.request(api.AuthLoginByWeixin, that.data.userData, 'POST').then(function (res) {
          console.log(res);
          if (res.code == 0) {
            console.log(res.data.userid);
            wx.setStorageSync('userids', res.data.userid);
            wx.navigateTo({
              url: '../orderlist/orderlist'
            })
          }
        });
      }
    })
  }
})
